class SlaTemplateController < ApplicationController
  def index

    begin



      slatemplate=SlaTemplate.new(@cf_client)
      @slatemplates = slatemplate.find_all_sla_templates()
      puts"@slatemplates=#{@slatemplates}"
      puts"come  in  index"
      slainstance=SlaInstance.new(@cf_client)
      @slainstances = slainstance.find_all_sla_instances()
      puts"@slainstances=#{@slainstances}"
      @available_instances = find_available_instances('STOPPED', 1, 0)
      available_memsizes = find_available_memsizes('STOPPED', 0, 1)
      @available_memsizes = []
      available_memsizes.each do |key, value|
        @available_memsizes << [value, key]
      end
      available_disksizes =select_disksizes()
      @available_disksizes = []
      available_disksizes.each do |key, value|
        @available_disksizes << [value, key]
      end



      @available_frameworks = find_available_frameworks_runtimes()                           #返回一个数组
      @available_services = find_available_services()
      @instances = 1

      puts"@available_instances=#{@available_instances}"
      puts"@available_memsizes=#{@available_memsizes}"
      puts"@available_frameworks=#{@available_frameworks}"
      puts"@available_services=#{@available_services}"
      puts"@available_disksizes=#{@available_disksizes}"
      puts"come  out  index"
    rescue Exception => ex
      flash[:alert] = ex.message
    end

  end





  def create

    @name = params[:name]
    @instances = params[:instances]
    @memsize = params[:memsize]
    @disksize = params[:disksize]
    @service = params[:service]
    @framework=params[:framework]
    @runtime=params[:runtime]
    @app_starttime = params[:app_starttime]
    @app_stoptime =params[:app_stoptime]
    @price= params[:price]
    @fine= params[:fine]


    if @name.blank?
      flash[:alert] = I18n.t('sla_templates.controller.name_blank')
    elsif @instances.blank?
      flash[:alert] = I18n.t('sla_templates.controller.instances_blank')
    elsif @memsize.blank?
      flash[:alert] = I18n.t('sla_templates.controller.memsize_blank')
    elsif @disksize.blank?
      flash[:alert] = I18n.t('sla_templates.controller.disksize_blank')
    elsif @framework.blank?
      flash[:alert] = I18n.t('sla_templates.controller.framework_blank')
    elsif @runtime.blank?
      flash[:alert] = I18n.t('sla_templates.controller.runtime_blank')
    elsif @service.blank?
      flash[:alert] = I18n.t('sla_templates.controller.service_blank')
    elsif @app_starttime.blank?
      flash[:alert] = I18n.t('sla_templates.controller.app_starttime_blank')
    elsif @app_stoptime.blank?
      flash[:alert] = I18n.t('sla_templates.controller.app_stoptime_blank')
    elsif @price.blank?
      flash[:alert] = I18n.t('sla_templates.controller.price_blank')
    elsif @fine.blank?
      flash[:alert] = I18n.t('sla_templates.controller.fine_blank')
    else

      begin
        slatemplate=SlaTemplate.new(@cf_client)
        begin
          sla_template_info = slatemplate.find(@name)
        rescue
          sla_template_info = nil
        end
        if sla_template_info.nil?
          slatemplate.create(@name, @instances, @memsize,@disksize, @framework, @runtime, @service,@app_starttime,@app_stoptime,@price,@fine)

          sla_template_info = slatemplate.find(@name)
          puts"slatemplate_info=#{sla_template_info}"
          @new_sla_template = [] << sla_template_info
          puts"@new_sla_template=#{sla_template_info}"
          flash[:notice] = I18n.t('sla_templates.controller.sla_created', :name => @name)
        else
          flash[:alert] = I18n.t('sla_templates.controller.already_exists')
        end
      rescue Exception => ex
        flash[:alert] = ex.message
      end
    end

    respond_to do |format|
      format.html { redirect_to sla_templates_info_url }
      format.js { flash.discard }
    end
  end





  def delete


    @name = params[:name]
    if @name.blank?
      flash[:alert] = I18n.t('sla_templates.controller.name_blank')
    else
      begin
        @name = @name.strip
        sla_template = SlaTemplate.new(@cf_client)

        sla_template.delete(@name)
        puts"delete :name=#{@name}"
        flash[:notice] = I18n.t('sla_templates.controller.sla_deleted', :name => @name)
      rescue Exception => ex
        flash[:alert] = ex.message
      end
    end
    respond_to do |format|
      format.html { redirect_to sla_templates_info_url }
      format.js { flash.discard }
    end
  end




  def create_instance
    @name = params[:names]
    @instances = params[:instances]
    @memsize = params[:memsize]
    @disksize = params[:disksize]
    @type = params[:type]
    @service = params[:service]
    @app_starttime = params[:app_starttime]
    @app_stoptime =params[:app_stoptime]
    @monthmode= params[:monthmode]
    @instancemode= params[:instancemode]
    @price=params[:price]
    @fine= params[:fine]
    puts "@app_starttime=#{@app_starttime}"
    puts "@app_stoptime=#{@app_stoptime}"
    puts "@disksize=#{@disksize}"
    puts "@fine=#{@fine}"
    puts "@type=#{@type}"
    puts "@monthmode=#{@monthmode}"


    if @name.blank?                                        #判断输入是否不满足要求
      flash[:alert] = I18n.t('apps.controller.name_blank')
    elsif @instances.blank?
      flash[:alert] = I18n.t('apps.controller.instances_blank')
    elsif @memsize.blank?
      flash[:alert] = I18n.t('apps.controller.memsize_blank')
    elsif @disksize.blank?
      flash[:alert] = I18n.t('apps.controller.disksize_blank')
    elsif @type.blank?
      flash[:alert] = I18n.t('apps.controller.type_blank')
    elsif @service.blank?
      flash[:alert] = I18n.t('apps.controller.service_blank')
    elsif @app_starttime.blank?
      flash[:alert] = I18n.t('apps.controller.app_starttime_blank')
    elsif @app_stoptime.blank?
      flash[:alert] = I18n.t('apps.controller.app_stoptime_blank')
                                                           #elsif (@app_starttime=~ /^(#{/[1-9]\d\d\d/}\.#{/0?[1-9]|1[12]/}\.#{/0?[1-9]|[12]\d|3[01]/}) (#{/[01]?[1-9]|2[0-4]/}:#{/[0-5]\d/}:#{/[0-5]\d/})$/).nil?
                                                           #  flash[:alert] = I18n.t('sla_instances.model.app_starttime_invalid')
                                                           #elsif (@app_stoptime=~ /^(#{/[1-9]\d\d\d/}\.#{/0?[1-9]|1[12]/}\.#{/0?[1-9]|[12]\d|3[01]/}) (#{/[01]?[1-9]|2[0-4]/}:#{/[0-5]\d/}:#{/[0-5]\d/})$/).nil?
                                                           #  flash[:alert] = I18n.t('sla_instances.model.app_stoptime_invalid')
    elsif  (DateTime.parse(@app_starttime).to_i)>(DateTime.parse(@app_stoptime).to_i)
      flash[:alert] = I18n.t('sla_instances.model.time_no_match')
    elsif  @monthmode.blank?&& @instancemode.blank?
      flash[:alert] = I18n.t('apps.controller.mode_blank')
    elsif  @monthmode&&@instancemode
      flash[:alert] = I18n.t('apps.controller.mode_more')
    elsif  @price.blank?
      flash[:alert] = I18n.t('apps.controller.price_blank')
    elsif  @fine.blank?
      flash[:alert] = I18n.t('apps.controller.fine_blank')     # 只能包括数字和小数点的正则表达式

      #elsif  (@price=~ /^[0-9]{1}([0-9]|[.])*$/).nil
      #  flash[:alert] = I18n.t('apps.controller.price_match')
      #elsif  (@fine=~ /^[0-9]{1}([0-9]|[.])*$/).nil
      #  flash[:alert] = I18n.t('apps.controller.fine_match')
    else        #满足情况，上传
      begin
        @name = @name.strip.downcase
        framework, runtime = @type.split("/")
        if  @monthmode
          @pricing_mode="month"
        else
          @pricing_mode="instance"
        end

        slainstance = SlaInstance.new(@cf_client)
        begin
          sla_instance_info = slainstance.find(@name)
        rescue
          sla_template_info = nil
        end
        if  sla_instance_info.nil?
          slainstance.create(@name, @instances, @memsize,@disksize, framework, runtime, @service,@app_starttime,@app_stoptime,@price,@fine,@pricing_mode)        #创建app
          sla_instance_info = slainstance.find(@name)
          puts"slainstance_info=#{sla_instance_info}"
          @new_sla_instance = [] << sla_instance_info
          puts"@new_sla_template=#{sla_instance_info}"
          flash[:notice] = I18n.t('sla_instances.controller.sla_created', :name => @name)
        else
          flash[:alert] = I18n.t('sla_instances.controller.already_exists')
        end

      rescue Exception => ex
        flash[:alert] = ex.message
      end
    end
    respond_to { |format|
      format.html { redirect_to sla_templates_info_url }
      format.js { flash.discard }

    }
  end


  def delete_instance


    @name = params[:name]
    puts "delete name=#{@name}"
    if @name.blank?
      flash[:alert] = I18n.t('sla_instances.controller.name_blank')
    else
      begin
        @name = @name.strip
        sla_instance = SlaInstance.new(@cf_client)

        sla_instance.delete(@name)
        puts"delete :name=#{@name}"
        flash[:notice] = I18n.t('sla_instances.controller.sla_deleted', :name => @name)
      rescue Exception => ex
        flash[:alert] = ex.message
      end
    end
    respond_to do |format|
      format.html { redirect_to sla_templates_info_url }
      format.js { flash.discard }
    end
  end


  def show
    @name = params[:name]
    if @name.blank?
      flash[:alert] = I18n.t('sla_instances.controller.name_blank')
      redirect_to sla_templates_info_url
    else
      begin
        @name = @name.strip
        slainstance = SlaInstance.new(@cf_client)
        @sla_instance_info = slainstance.find(@name)

        puts"@sla_instance_info=#{@sla_instance_info}"
        #@sla_instance_info = [] << sla_instance_info

        @memsize = @sla_instance_info[:memsize]
        @disksize = @sla_instance_info[:disksize]
        @instances = @sla_instance_info[:instances]
        @framework=@sla_instance_info[:framework]
        @runtime=@sla_instance_info[:runtime]
        @service = @sla_instance_info[:service]
        @app_starttime = @sla_instance_info[:app_starttime]
        @app_stoptime =@sla_instance_info[:app_stoptime]
        @price=@sla_instance_info[:price]
        @fine=@sla_instance_info[:fine]
        @fine=@sla_instance_info[:fine]
        @pricing_mode=@sla_instance_info[:pricing_mode]
        puts "@instances=#{@memsize}"
        puts "@instances=#{@instances}"

      rescue CloudFoundry::Client::Exception::NotFound => ex
        flash[:alert] = ex.message
        redirect_to sla_templates_info_url
      rescue Exception => ex
        flash[:alert] = ex.message
      end
    end
  end



  def find_available_instances(app_state, app_memsize, app_instances)
    system = System.new(@cf_client)
    available_for_use = system.find_available_memory()
    if app_state != 'STOPPED'
      available_for_use = available_for_use + (app_memsize.to_i * app_instances.to_i)
    end
    available_instances = available_for_use.to_i / app_memsize.to_i
  end

  def find_available_memsizes(app_state, app_memsize, app_instances)
    system = System.new(@cf_client)
    available_for_use = system.find_available_memory()
    if app_state != 'STOPPED'
      available_for_use = available_for_use + (app_memsize.to_i * app_instances.to_i)
    end

    available_memsizes = {}
    available_memsizes[64] = "64 Mb" if available_for_use >= (64 * app_instances.to_i)
    available_memsizes[128] = "128 Mb" if available_for_use >= (128 * app_instances.to_i)
    available_memsizes[256] = "256 Mb" if available_for_use >= (256 * app_instances.to_i)
    available_memsizes[512] = "512 Mb" if available_for_use >= (512 * app_instances.to_i)
    available_memsizes[1024] = "1 Gb" if available_for_use >= (1024 * app_instances.to_i)
    available_memsizes[2048] = "2 Gb" if available_for_use >= (2048 * app_instances.to_i)
    if available_memsizes.empty?
      available_memsizes[""] = I18n.t('apps.controller.no_memory')
    else
      if app_memsize > 0
        available_memsizes["selected"] = app_memsize
      end
    end
    available_memsizes
  end

  def select_disksizes()
    available_disksizes = {}
    available_disksizes[512] = "512 Mb"
    available_disksizes[1024] = "1 Gb"
    available_disksizes[2048] = "2 Gb"
    available_disksizes[4096] = "4 Gb"
    available_disksizes
  end


  def find_available_frameworks_runtimes()
    available_frameworks = []
    system = System.new(@cf_client)
    frameworks = system.find_all_frameworks()
    if frameworks.empty?
      available_frameworks << [I18n.t('apps.controller.no_frameworks'), ""]
    else
      available_frameworks << [I18n.t('apps.controller.select_framework'), ""]
      frameworks.each do |fwk_name, fwk|
        fwk[:runtimes].each do |run|
          available_frameworks << [fwk[:name].capitalize + " " + I18n.t('apps.controller.fwk_on_run') + " " + run[:description], fwk_name.to_s + "/" + run[:name].to_s]
        end
      end
    end
    available_frameworks
  end



  def find_available_services
    available_services = []
    service = Service.new(@cf_client)
    provisioned_services = service.find_all_services()
    if provisioned_services.empty?
      available_services << [I18n.t('apps.controller.no_services'), ""]
    else
      available_services << [I18n.t('apps.controller.select_service'), ""]
      provisioned_services.each do |service_info|
        available_services << [service_info[:name] + " (" + service_info[:vendor] + " " + service_info[:version] + ")", service_info[:name]]
      end
    end
    available_services
  end

end
